<template>
  <div class="container">
    <div class="btn" style="margin-bottom: 20px">
      <input type="text" id="search" />
      <!-- <el-button type="primary" size="default" @click="handleSet">测试</el-button> -->
      
    </div>
    <div id="map" ref="map"></div>
  </div>
</template>

<script>
import { getDeviceList } from "@/api/device";
import { Message } from "element-ui";
export default {
  data() {
    return {
      search: "",
      map: null,
      latitude: null,
      longitude: null,
      markers: [],
      deives: [],
    };
  },
  mounted() {
     // 动态加载地图API
     const script = document.createElement("script");
    script.src = `https://mapapi.cloud.huawei.com/mapjs/v1/api/js?callback=initMap&key=${encodeURIComponent(
      "DgEDAK9IRPUY9N+PMYjkFmELYMVAS792Ezw+vOe/hCTj6/4MmyEHYAn7y80NuOSLl3u1nk9LxBLClziTIgN0FT0C/6ZS7jig/e+n8Q=="
    )}`;
    script.async = true;
    script.defer = true;
    document.head.appendChild(script);
    window.initMap = this.initMap;

    // this.getLocation();
    // setTimeout(() => {
    //   let tags = document.getElementsByClassName("deviceItem");
    //   console.log(tags.length, "tags");
    //   tags.forEach((el) => {
    //     el.onclick = function (e) {
    //       console.log(e.target.id);
    //     };
    //   });
    // }, 2000);
  },
  methods: {
    handleSet(){
      console.log(this.map)
      window.MAP.setZoom(10)
    },
    async init() {
      const res = await getDeviceList({
        pageIndex: 1,
        pageSize: 100,
      });
      if (!res.status) {
        res.content.forEach((item) => {
          if (item.lat && item.lng) {
            this.deives.push(item);
          }
        });
        setTimeout(() => {
          this.addMarkes();
        }, 1000);
      }
    },
    getLocation() {
      // 检查浏览器是否支持 Geolocation API
      if ("geolocation" in navigator) {
        const options = {
          enableHighAccuracy: true, // 是否高精度定位
          timeout: 5000, // 超时时间（毫秒）
          maximumAge: 0, // 是否使用缓存位置
        };

        // 调用 API 获取位置
        navigator.geolocation.getCurrentPosition(
          (position) => {
            this.latitude = position.coords.latitude;
            this.longitude = position.coords.longitude;
            this.map &&
              this.map.setCenter({
                lat: this.latitude,
                lng: this.longitude,
              });
          },
          (error) => {
            const errorTypes = ["权限被拒绝", "位置不可用", "请求超时"];
            Message.warning(`定位失败：${errorTypes[error.code - 1]}`);
          }
        );
      } else {
        Message.warning("当前浏览器不支持地理位置获取");
      }
    },
    initMap() {
      var mapOptions = {};
      mapOptions.center = { lat: 28.23529, lng: 112.93134 };
      mapOptions.zoom = 16;
      mapOptions.minZoom = 2;
      mapOptions.maxZoom = 20;
      mapOptions.language = "CHI";
      mapOptions.mapType = "TERRAIN";
      mapOptions.locationControl = true;
      mapOptions.navigationControl = true;
      mapOptions.presetStyleId = "simple"; //standard、night、simple。
      mapOptions.sourceType = "vector";
      this.$nextTick(() => {
        this.map = new HWMapJsSDK.HWMap(this.$refs.map, mapOptions);
        window.MAP = this.map
        this.init();
        var searchBoxInput = document.getElementById("search");
        var acOptions = {
          radius: 10000,
          countryCode: "CN",
          language: "zh",
          poiType: "GEOCODE",
        };
        var autocomplete = new HWMapJsSDK.HWAutocomplete(
          searchBoxInput,
          acOptions
        );
        const _this = this
        autocomplete.addListener("site_changed", function () {
          var site = autocomplete.getSite();
          if (site) {
            console.log("选中地址：", site);
            _this.map.setCenter({ lat: site.location.lat, lng: site.location.lng });
            console.log( _this.map.setCenter)
          }
        });
      });
    },
    addMarkes() {
      this.map.setCenter({ lat: this.deives[0].lat, lng: this.deives[0].lng });

      for (let i = 0; i < this.deives.length; i++) {
        var opts = {
          position: this.deives[i],
          zIndex: 10,
          animation: "DROP",
          // label: {
          //   text: this.deives[i].imei,
          //   offsetY: 10,
          //   fontSize: "14px",
          //   color: "red",
          // },
          icon: {
            url: require("../../../assets/404_images/dot.png"),
          },
        };
        this.markers.push(new HWMapJsSDK.HWMarker(opts));

        const markerCluster = new HWMapJsSDK.HWMarkerCluster(
          this.map,
          this.markers
        );
        markerCluster.addListener("click", (res) => {
          console.log(res, "xx");

          this.map.setCenter({
            lat: res.markers[0].position.lat,
            lng: res.markers[0].position.lng,
          });
          this.map.setZoom(18);
        });

        const infoWindow = new HWMapJsSDK.HWInfoWindow({
          map: this.map,
          content: `<div class="deviceItem" id=${this.deives[i].id}>
             <div>设备号：${this.deives[i].imei}</div>
             <div>状态：${this.deives[i].state == 1 ? "在线" : "离线"}</div>
             <div>型号：${
               this.deives[i].model ? this.deives[i].model : "未知"
             }</div>
            </div>`,
          offset: [0, -40],
        });
        // 在标记为A的marker处打开一个信息窗
        infoWindow.open(new HWMapJsSDK.HWMarker(opts));
        infoWindow.addListener("close", (res) => {
          console.log(res, "x");
        });
      }
    },
    handleMakeLne() {
      const naviLineOption = {
        points: [
          { lng: 113.394063, lat: 23.041201 },
          { lng: 113.398787, lat: 23.037327 },
        ],
        strokeColor: "red",
        strokeWidth: 20,
        fillColor: "red",
        fillWidth: 5,
        animateOption: {
          animate: true,
        },
      };
      const naviLine = new HWMapJsSDK.HWNaviLine(naviLineOption);
      naviLine.setMap(this.map);
    },
  },
};
</script>

<style scoped>
#map {
  margin-top: 20px;
  height: 700px;
  width: 100%;
  margin: 0 auto;
}

</style>
